package com.LensBlaster.upload.Flickr;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.widget.ImageView;

import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.REST;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.auth.Auth;
import com.aetrion.flickr.auth.AuthInterface;
import com.aetrion.flickr.auth.Permission;
import com.aetrion.flickr.uploader.UploadMetaData;
import com.aetrion.flickr.uploader.Uploader;

/**
 * Handles the process of uploading an image to Flickr.
 */
public class Upload extends Activity {

	private static final int ACTIVITY_AUTH = 0;
	public static final String PREFERENCES = "lensblaster";
	private static final int DIALOG1_KEY = 0;

	private Uri mImageURI = null;
	private String frob = null;
	private AuthInterface ai = null;

	/**
	 * Starts the upload process and stores the image URI passed in with
	 * Intent.setData().
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Clear stored token and cookies -- For testing purposes ONLY!
		/*
		 * CookieSyncManager.createInstance(this); CookieManager cm =
		 * CookieManager.getInstance(); cm.removeAllCookie(); SharedPreferences
		 * sp = getSharedPreferences(PREFERENCES,0); Editor ed = sp.edit();
		 * ed.clear(); ed.commit();
		 */
		// ////////////////////////////////////////////////////////
		// Get the image URI
		Intent i = this.getIntent();
		mImageURI = i.getData();

		// Show the image
		ImageView iv = new ImageView(this);
		iv.setImageURI(mImageURI);
		setContentView(iv);

		// Display indeterminate upload progress indicator
		showDialog(DIALOG1_KEY);

		// Create a new thread for uploading, so that the UI
		// can be updated.
		Thread t = new Thread(new Runnable() {
//			@Override
			public void run() {
				upload();
			}
		});
		t.start(); // Start uploading in a new thread
	}

	/**
	 * Attempt to upload the image specified by the data URI, starting
	 * the WebAuthentication activity if the user needs to authorize LensBlaster.
	 */
	public void upload() {
		try {

			SharedPreferences sp = getSharedPreferences(PREFERENCES, 0);
			String apiKey = "db2c17824c5028cf29b663bccf79fef6";
			String sSecret = "8666d98fd91e78b3";

			// Arbitrarily return a junk default value of "-1" if token is not
			// present
			String token = sp.getString("token", "-1");
			android.util.Log.d("lens", "token from preferences = " + token);

			// Set up Flickr objects
			Uploader uploader = new Uploader(apiKey, sSecret);
			REST rest = new REST();
			RequestContext requestContext = RequestContext.getRequestContext();
			ai = new AuthInterface(apiKey, sSecret, rest);

			// Validate token, retrieve new one if necessary and store to file
			Auth validToken;
			try {
				validToken = ai.checkToken(token);
			} catch (FlickrException e) {
				
				getNewToken(); // Current token is invalid, get a new one.
				return;
				
			}

			// Valid token, Prepare for upload
			requestContext.setAuth(validToken);
			UploadMetaData umd = new UploadMetaData();
			umd.setTitle("");
			android.util.Log.d("lens", "Uploading file: " + mImageURI.getPath());
			FileInputStream is = new FileInputStream(new File(mImageURI.getPath()));
			BufferedInputStream in = new BufferedInputStream(is);

			// Upload
			String photoId = uploader.upload(in, umd);
			android.util.Log.d("lens", "Finished uploading");
			in.close();
			is.close();

			// Return to previous activity with "success" result
			Intent i = new Intent();
			setResult(RESULT_OK, i);
			finish(); // return to photoview

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// Get a new token by sending the user to an authentication URL
	private void getNewToken() {
		android.util.Log.d("lens", "Retrieving new token");

		// Request frob
		try {
			frob = ai.getFrob();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// Build authentication URL
		URL authURL = null;
		try {
			authURL = ai.buildAuthenticationUrl(Permission.WRITE, frob);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		android.util.Log.d("lens", "Auth URL = " + authURL.toString());
		try {
			// Star the web authentication activity
			Intent i = new Intent(this, WebAuthentication.class);
			i.putExtra(android.app.SearchManager.QUERY, authURL.toString());
			startActivityForResult(i, ACTIVITY_AUTH);

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * After the WebAuthentication activity has finished, attempt to retrieve
	 * the authentication token and restart the upload process.
	 * 
	 * @param requestCode The code packaged in the finsihed activity's intent.
	 * @param resultCode Indicates the success or failure of the called activity.
	 * @param intent The result intent.
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		android.util.Log.d("lens", "returned to main activity");

		Auth token = null;
		try {
			token = ai.getToken(frob); // Request new token

			// Store the token for later uploads
			SharedPreferences sp = getSharedPreferences(PREFERENCES, 0);
			Editor e = sp.edit();
			e.putString("token", token.getToken());
			e.commit();

			// Restart the upload process in a new thread
			Thread t = new Thread(new Runnable() {
//				@Override
				public void run() {
					upload();
				}
			});
			t.start(); // Start uploading (again) in a new thread

		} catch (Exception e) {
			android.util.Log.e("lens", "error retrieving token");
			e.printStackTrace();

			// There was an error, so return to previous activity
			Intent i = new Intent();
			setResult(RESULT_CANCELED, i);
			finish(); // return to photoview
		}
	}

	/**
     * Show a progress dialog for uploading.
     * 
     * @param id The id of the ProgressDialog.
     * @return The dialog to display.
     */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case (DIALOG1_KEY):
			ProgressDialog dialog = new ProgressDialog(this);
			// dialog.setTitle("Uploading");
			dialog.setMessage("Uploading photo to Flickr...");
			dialog.setIndeterminate(true);
			dialog.setCancelable(false);
			return dialog;
		}
		return null;

	}

}